package com.thinkTank.oa.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.thinkTank.oa.common.Constant;
import com.thinkTank.oa.common.SystemGlobals;
import com.thinkTank.oa.common.UserInfo;
import com.thinkTank.oa.entity.ConfOfAttr;
import com.thinkTank.oa.entity.Conference;
import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.entity.Person;
import com.thinkTank.oa.entity.Subscribe;
import com.thinkTank.oa.service.ConOfAttrService;
import com.thinkTank.oa.service.ConferenceService;
import com.thinkTank.oa.service.CustomerService;
import com.thinkTank.oa.service.DictiontryService;
import com.thinkTank.oa.service.PersonService;
import com.thinkTank.oa.service.ProjectService;
import com.thinkTank.oa.service.SubscribeService;
import com.thinkTank.oa.util.ExcelUtil;
import com.thinkTank.oa.util.FileUtils;
import com.thinkTank.oa.util.StrUtil;

@Controller
@RequestMapping("/conference")
public class ConferenceController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(ConferenceController.class);
	@Resource
	private DictiontryService dictiontryService;

	@Resource
	private ProjectService projectService;

	@Resource
	private ConferenceService conferenceService;

	@Resource
	private CustomerService customerService;

	@Resource
	private PersonService personService;

	@Resource
	private ConOfAttrService conOfAttrService;
	
	@Autowired
	private SubscribeService subscribeService;

	/** 将常用的list封装到Model中 */
	private void addListToModel(Model model) {
		/**
		 * 用于修改页面的回显
		 */
		// 项目来源
		List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();
		// 所属领域
		List<Dictiontry> researchFieldDictiontryList = getResearchField();
		// 专家类型
		List<Dictiontry> personTypeList = getPersonType();
		// 人才级别
		List<Dictiontry> talentLevelListByDic = getTalentLevel();

		/**
		 * 用于专家添加页面中的遍历
		 */
		// 专家来源
		List<Dictiontry> sourceList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PROJECTSOURCE);
		// 专家类型
		List<Dictiontry> typeList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_PERSONTYPE);
		// 所属领域
		List<Dictiontry> fieldList =SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_DEMANDFIELD);
		// 人才级别
		List<Dictiontry> talentLevelList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_TALENTLEVEL);
		/**
		 * 用于显示对接详情添加页面的遍历
		 */
		// 对接状态下拉列表
		List<Dictiontry> buttStatus = getButtStatus();
		// 所有国家
		List<Dictiontry> countryDictiontryList = SystemGlobals.getInstance()
				.getDictiontryMap(Constant.DICTIONTRY_COUNTRY);
		model.addAttribute("countryDictiontryList", countryDictiontryList);

		model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
		model.addAttribute("personTypeList", personTypeList);
		model.addAttribute("talentLevelListByDic", talentLevelListByDic);
		model.addAttribute("sourceList", sourceList);
		model.addAttribute("typeList", typeList);
		model.addAttribute("fieldList", fieldList);
		model.addAttribute("talentLevelList", talentLevelList);
		model.addAttribute("buttStatus", buttStatus);
	}

	@RequestMapping(value = "/addConference")
	public String addConference(Model model) {

		addListToModel(model);
		if (!model.containsAttribute("conference")) {
			model.addAttribute("conference", new Conference());
		}

		if (!model.containsAttribute("researchFieldArr")) {
			model.addAttribute("researchFieldArr", "");
		}
		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();
		// 项目来源
		List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
		// 研究领域
		List<Dictiontry> researchFieldDictiontryList = getResearchField();
		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
		model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
		return "addConfrence";
	}

	@RequestMapping(value = "/saveConference", method = RequestMethod.POST)
	public String saveConference(@Valid Conference conference, BindingResult bindingResult,
			MultipartFile conferenceFiles, Model model, HttpServletRequest request) {

		// 表单验证逻辑
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 获取地区相关数据，便于回显
				String areaId = conference.getArea();
				String cityId = "";
				String province = "";
				if (StringUtil.isNotEmpty(areaId)) {
					if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
						// 说明是区的id
						// 截取得到省和市的id
						cityId = areaId.substring(0, 5);
						province = areaId.substring(0, 2);
						model.addAttribute("areaId", areaId);
						model.addAttribute("cityId", cityId);
						model.addAttribute("province", province);
					}
					if (areaId.length() < 3 && areaId.length() > 0) {
						// 说明是省的id
						model.addAttribute("province", areaId);
					}
					if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
						// 说明是市的id
						// 截取得到省和市的id
						cityId = areaId;
						province = areaId.substring(0, 2);
						model.addAttribute("province", province);
						model.addAttribute("cityId", cityId);
					}

					// 所有市
					List<Dictiontry> cityDictiontryList = getCityByProvince(province);
					// 所有区
					List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);

					model.addAttribute("cityDictiontryList", cityDictiontryList);
					model.addAttribute("areaDictiontryList", areaDictiontryList);
				}

				// 发生错误，直接return
				String[] researchFieldArr = null;
				if (StringUtil.isNotEmpty(conference.getResearchField())) {
					researchFieldArr = conference.getResearchField().split(",");
				}
				if (researchFieldArr != null) {
					model.addAttribute("researchFieldArr", researchFieldArr);
				} else {
					model.addAttribute("researchFieldArr", "");
				}

				if(conference.getDomesticOrForeign()!=null){
					if (conference.getDomesticOrForeign() == 1 && areaId!=null) {
						model.addAttribute("countryId", Integer.parseInt(areaId));
					}
				}

				model.addAttribute("conference", conference);
				return addConference(model);
			}
		}

		if (null != conferenceFiles && !conferenceFiles.isEmpty()) {
			// 文件名字
			String fileName = conferenceFiles.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("conference", fileName);

			conference.setConferenceFile(oldFileName);
			try {
				FileUtils.uploadFile(conferenceFiles.getBytes(), Constant.DEF_CONF_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}

		conference.setPid(StrUtil.getUUID32());
		// 转化为二进制保存
		conference.setResearchFieldInteger(StrUtil.stringByByte(conference.getResearchField()));

		// 保存会议活动数据
		conferenceService.add(conference);
		//System.out.println("保存成功");
		return "redirect:/conference/conferenceList";
	}

	/**
	 * 会议活动列表展示数据来源
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/conferenceList")
	public String conferenceList(Conference conference, BindingResult bindingResult, Integer pageNum, Model model,
			@RequestParam(value = "conferenceNumberId", required = false) String conferenceNumberId, HttpServletRequest request) {

		addListToModel(model);
		String cityId = "";
		String province = "";

		if (StringUtil.isNotEmpty(conference.getArea()) && conference.getDomesticOrForeign()!=null) {
			areaModel(model, conference.getArea(), conference.getDomesticOrForeign());
		}
		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		

		String conferenNum = "";

		// 重新复制客户id
		if (StringUtil.isNotEmpty(conferenceNumberId)) {
			conferenNum = String.valueOf(conferenceNumberId.trim());
			// 去除字母
			conferenNum = conferenNum.replaceAll("[a-zA-Z]", "");
		}
		if (StringUtil.isNotEmpty(conferenNum)) {
			conference.setConferenceNumber(Integer.parseInt(conferenNum));
		}
		if (StringUtil.isNotEmpty(conference.getConferenceName())) {
			conference.setConferenceName(conference.getConferenceName().trim());
		}
		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(conference.getResearchField())) {
			researchFieldArr = conference.getResearchField().split(",");
			conference.setResearchFieldNumber(researchFieldArr.length);
			conference.setResearchFieldInteger(StrUtil.stringByByte(conference.getResearchField()));
		}
		model.addAttribute("researchFieldArr", researchFieldArr);

		// 查询所有会议活动数据
		PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
		List<Conference> conList = conferenceService.queryAllConference(conference);

		for (int i = 0; i < conList.size(); i++) {
			String areaStr = "";
			String reachName = "";
			// 得到所属领域二进制
			String rearch = conList.get(i).getResearchField();
			// 得到areaId
			String areaIdStr = String.valueOf(conList.get(i).getArea());
			if (areaIdStr != null && !"".equals(areaIdStr) && !"null".equals(areaIdStr)) {
				if (areaIdStr.length() == 4) {
					// 说明是国外的
					Dictiontry dicArea = new Dictiontry();
					dicArea.setPid(Integer.parseInt(areaIdStr));
					dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
					// 国外的名字
					areaStr=getAreaWorth(areaIdStr, 1);
				}

				if (areaIdStr.length() < 10 && areaIdStr.length() > 5) {
					// 说明是区的id
					// 截取得到省和市的id
					Dictiontry dicArea = new Dictiontry();
					dicArea.setNames(areaIdStr);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA);
					// 区的名字
//					areaStr = dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "  ";
//
//					cityId = areaIdStr.substring(0, 5);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
//					dicArea.setNames(cityId);
//					// 市的名字
//					areaStr += dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "  ";
//
//					province = areaIdStr.substring(0, 2);
//					dicArea.setNames(province);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
//					// 省的名字
//					areaStr += dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "";
//					
					areaStr=getAreaWorth(areaIdStr, 0);
				}

				if (areaIdStr.length() < 6 && areaIdStr.length() > 2 && areaIdStr.length() != 4) {
					// 说明是市的id
					Dictiontry dicArea = new Dictiontry();
					cityId = areaIdStr.substring(0, 5);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
					dicArea.setNames(cityId);
					// 市的名字
//					areaStr += dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "  ";
//
//					province = areaIdStr.substring(0, 2);
//					dicArea.setNames(province);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
//					// 省的名字
//					areaStr += dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "";

					areaStr=getAreaWorth(areaIdStr, 0);
				}

				if (areaIdStr.length() < 3 && areaIdStr.length() > 0) {
					// 说明是省的id
					Dictiontry dicArea = new Dictiontry();
					province = areaIdStr.substring(0, 2);
					dicArea.setNames(province);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// 省的名字
//					areaStr += dictiontryService.findDictiontryByNamesAndGroupName(dicArea).get(0).getWorth() + "";
					areaStr=getAreaWorth(areaIdStr, 0);
				}
			}
			// 给地区附上名字
			conList.get(i).setAreaNameStr(areaStr);
			//取最右地区
			if(areaStr.contains("-")){
				String [] areaArray=areaStr.split("-");
				String lastArea=areaArray[areaArray.length-1];
				conList.get(i).setAreaNameArray(lastArea);
			}else{
				conList.get(i).setAreaNameArray(areaStr);
			}

			// 二进制转化为字符串
//			String rearchStr = StrUtil.byteToString(rearch);
			reachName=getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
//			String[] reaArray = rearchStr.split(",");
//			for (String reaStr : reaArray) {
//				Dictiontry dic = new Dictiontry();
//				dic.setGroupName(Constant.DICTIONTRY_PROJECTFIELD);
//				dic.setNames(reaStr);
//				List<Dictiontry> dicList = dictiontryService.findDictiontryByNamesAndGroupName(dic);
//				for (Dictiontry dictiontry : dicList) {
//					reachName += dictiontry.getWorth() + "  ";
//				}
//			}
			conList.get(i).setResearchFieldNameStr(reachName);
		}
		
		  //查询已经关注的
        Subscribe subscribe = new Subscribe();
        subscribe.setSubType(5);//关注类型为会议
        subscribe.setUserid(getUserId(request));
        List<Subscribe> subList = subscribeService.queryAll(subscribe);
        List<String> subDemandIdList = subList.stream().map(Subscribe::getTypeObject).collect(Collectors.toList());
        model.addAttribute("subDemandIdList", subDemandIdList);

		// 将list放进PageInfo
		PageInfo<Conference> pageInfo = new PageInfo<Conference>(conList);
		// 传至前台页面展示
		model.addAttribute("pageInfo", pageInfo);
		return "conferencelist";
	}

	@RequestMapping(value = "/updateConference")
	public String updateConference(@RequestParam("pid") String pid, Model model) {

		addListToModel(model);

		// 根据pid查询到对应的会议活动数据
		Conference conference = conferenceService.getById(pid);
		if (!model.containsAttribute("conference")) {
			model.addAttribute("conference", conference);
		}
		String cityId = "";
		String province = "";
		String areaId = String.valueOf(conference.getArea());
		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
			// 说明是区的id
			// 截取得到省和市的id
			cityId = areaId.substring(0, 5);
			province = areaId.substring(0, 2);
			model.addAttribute("areaId", areaId);
			model.addAttribute("cityId", cityId);
			model.addAttribute("province", province);
		}
		if (areaId.length() < 3 && areaId.length() > 0) {
			// 说明是省的id
			model.addAttribute("province", areaId);
		}
		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
			// 说明是市的id
			// 截取得到省和市的id
			cityId = areaId;
			province = areaId.substring(0, 2);
			model.addAttribute("province", province);
			model.addAttribute("cityId", cityId);
		}

		if (conference.getDomesticOrForeign() == 1) {
			model.addAttribute("countryId", Integer.parseInt(areaId));
		}

		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();
		// 所有市
		List<Dictiontry> cityDictiontryList = getCityByProvince(province);
		// 所有区
		List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);
		// 项目来源
		List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
		// 研究领域
		List<Dictiontry> researchFieldDictiontryList = getResearchField();

		// 研究领域二进制转化为字符串
		String[] researchFieldArr = StrUtil.byteToString(conference.getResearchField()).split(",");
		model.addAttribute("researchFieldArr", researchFieldArr);

		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		model.addAttribute("cityDictiontryList", cityDictiontryList);
		model.addAttribute("areaDictiontryList", areaDictiontryList);

		model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
		model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
		model.addAttribute("pid", pid);
		return "conferenceupdate";
	}

	/**
	 * 保存修改会议数据
	 * 
	 * @param conference
	 * @param bindingResult
	 * @param conferenceFile
	 * @param customerIds
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/saveUpdateConference", method = RequestMethod.POST)
	public String saveUpdateConference(
			@RequestParam(value = "conferenceFiles", required = false) MultipartFile conferenceFiles,
			@Valid Conference conference, BindingResult bindingResult, Model model, HttpServletRequest request) {

		// 表单验证逻辑
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 发生错误，直接return
				model.addAttribute("conference", conference);
				return updateConference(conference.getPid(), model);
			}
		}

		if (null != conferenceFiles && !conferenceFiles.isEmpty()) {
			// 文件名字
			String fileName = conferenceFiles.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("conference", fileName);

			conference.setConferenceFile(oldFileName);
			try {
				FileUtils.uploadFile(conferenceFiles.getBytes(), Constant.DEF_CONF_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}else{
			String pid=conference.getPid();
			//修改时，若不上传附件，则不改变原附件路径
			String fileName=conferenceService.getById(pid).getConferenceFile();
			conference.setConferenceFile(fileName);
		}
		
		// 转化为二进制保存
		conference.setResearchFieldInteger(StrUtil.stringByByte(conference.getResearchField()));
		
		conference.setUpdateTime(StrUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
		
		// 保存会议活动数据
		conferenceService.update(conference);
		//System.out.println("保存成功");
		return "redirect:/conference/showDetail?conferenceId="+conference.getPid();
	}

	/**
	 * 添加演讲嘉宾跳转页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addConferenceGuest")
	public String addConferenceGuest(@RequestParam("pid") String pid, Model model, HttpServletRequest request) {

		if (!model.containsAttribute("person")) {
			model.addAttribute("person", new Person());
		}
		addListToModel(model);

		model.addAttribute("pid", pid);

		return "addConferenceGuest";
	}

	/**
	 * 添加演讲嘉宾方法
	 * 
	 * @param pid
	 * @param name
	 * @param email
	 * @param tell
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/saveConferenceGuest", method = RequestMethod.POST)
	public String saveConferenceGuest(@RequestParam("conferencePid") String conferencePid, @Valid Person person,
			BindingResult bindingResult, Model model, HttpServletRequest request) {

		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 发生错误，直接return
				model.addAttribute("person", person);
				return addConferenceGuest(conferencePid, model, request);
			}
		}
		// 通过pid查询到相关的会议数据
		Conference conference = conferenceService.getById(conferencePid);
		// 生成主键id
		String personId = StrUtil.getUUID32();

		if (StringUtil.isEmpty(person.getTell()) && StringUtil.isEmpty(person.getEmail())) {
			// 如果没有填邮箱和电话（暂不知道），则直接添加这个conferenceGuest这个字段
			conference.setConferenceGuest(
					conference.getConferenceGuest() + ";" + StrUtil.getUUID32() + ":" + person.getName());
			conferenceService.update(conference);
		} else {
			// 添加的持有人有电话，微信或者邮箱，就去数据库查这个人
			// 调用董力的接口，返回专家对象
			Person queryPerson = personService.findPersonByNameAndTellAndEmail(person);
			if (queryPerson == null) {
				// 先新增专家库数据
				person.setPid(personId);
				// 收集人（录入人）
				person.setCollectPersonId(getUserInfoBySession(request).getUserId());
				// 录入时间
				person.setEntryTime(StrUtil.getCurrentDateTime());
				// 转化为二进制保存
				person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
				// 再往中间表插入一条数据
				ConfOfAttr conofattr = new ConfOfAttr();
				conofattr.setConferenceId(conferencePid);
				conofattr.setPersonId(personId);
				conofattr.setPid(StrUtil.getUUID32());
				// 修改会议活动表中的嘉宾数据
				conference.setConferenceGuest(personId + ":" + person.getName());
				// 放在同一个事务中(新增专家，往中间表中插入数据，修改会议表中的嘉宾数据)
				conferenceService.update(person, conofattr, conference);
			} else {
				// 专家表中有对应的专家信息
				ConfOfAttr conofattr = new ConfOfAttr();
				conofattr.setConferenceId(conferencePid);
				conofattr.setPersonId(queryPerson.getPid());
				conofattr.setPid(StrUtil.getUUID32());
				// 直接保存专家表数据
				// 修改会议活动表中的嘉宾数据
				conference.setConferenceGuest(queryPerson.getPid() + ":" + person.getName());
				conferenceService.update(conofattr, conference);
			}

		}
		return "redirect:/confofattr/conferencePerson?pid=" + conferencePid;
	}

	/**
	 * 修改演讲嘉宾跳转页面
	 * 
	 * @param pid
	 *            会议Id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/updateConferenceGuest")
	public String updateConferenceGuest(@RequestParam("pid") String pid, Model model) {

		// 根据pid查询到对应的会议活动数据
		Conference conference = conferenceService.getById(pid);
		// 取出嘉宾conferenceGuest这个字段数据
		String conferenceGuest = conference.getConferenceGuest();
		// 获取专家id
		String personId = "";
		if (conferenceGuest.contains(":")) {
			personId = conferenceGuest.substring(0, conferenceGuest.indexOf(":"));
		}
		// 通过专家id，查询到专家表数据
		Person person = personService.getById(personId);

		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();

		model.addAttribute("conferencePid", pid);
		model.addAttribute("person", person);
		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		return "updateConferenceGuest";
	}

	/**
	 * 修改演讲嘉宾方法
	 * 
	 * @param conferencePid
	 * @param person
	 * @param bindingResult
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/saveUpdateConferenceGuest", method = RequestMethod.POST)
	public String saveUpdateConferenceGuest(@RequestParam("conferencePid") String conferencePid, Person person,
			BindingResult bindingResult, Model model, HttpServletRequest request) {

		// 通过pid查询到相关的会议数据
		Conference conference = conferenceService.getById(conferencePid);
		// 生成主键id
		String personId = StrUtil.getUUID32();
		// 获取当前登录信息
		UserInfo userInfo = getUserInfoBySession(request);

		if (StringUtil.isEmpty(person.getTell()) && StringUtil.isEmpty(person.getEmail())) {
			// 如果没有填邮箱和电话（暂不知道），则直接修改这个conferenceGuest这个字段
			conference.setConferenceGuest(conference.getConferenceGuest() + "," + person.getName());
			conferenceService.update(conference);
		} else {
			// 添加的持有人有电话，微信或者邮箱，就去数据库查这个人
			// 调用董力的接口，返回专家对象
			Person queryPerson = personService.findPersonByNameAndTellAndEmail(person);
			if (queryPerson == null) {
				// 先新增专家库数据
				person.setPid(personId);
				// 再往中间表插入一条数据
				ConfOfAttr conofattr = new ConfOfAttr();
				conofattr.setConferenceId(conferencePid);
				conofattr.setPersonId(personId);
				// 修改会议活动表中的嘉宾数据
				conference.setConferenceGuest(personId + ":" + person.getName());
				// 放在同一个事务中(新增专家，往中间表中插入数据，修改会议表中的嘉宾数据)
				conferenceService.update(person, conofattr, conference);

			} else {
				// 专家表中有对应的专家信息
				ConfOfAttr conofattr = new ConfOfAttr();
				conofattr.setConferenceId(conferencePid);
				conofattr.setPersonId(queryPerson.getPid());
				// 直接保存中间表数据,修改会议活动表中的嘉宾数据
				conference.setConferenceGuest(queryPerson.getPid() + ":" + person.getName());
				conferenceService.update(conofattr, conference);
			}

		}
		return "redirect:/conference/conferenceList";
	}

	/**
	 * 会议活动添加客户id跳转页面
	 * 
	 * @param pid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addCustomer")
	public String addCustomer(@RequestParam("pid") String pid, Model model) {

		model.addAttribute("pid", pid);
		return "ConferenceAddCustomer";
	}
	
	
	 @RequestMapping("/showDetail")
	 public String showDetail(String conferenceId, Model model) {
	        Conference conference = conferenceService.getById(conferenceId);
//	        String [] personArray = null;
	        String conferenceGuestName="";
	        
	        //获取演讲嘉宾Id
	        List<ConfOfAttr> conofList=conOfAttrService.findAttrPersonByConfId(conferenceId);
	        //得到嘉宾id集合
	        List<String> personIdList=new ArrayList<String>();
	        for (ConfOfAttr conof : conofList) {
	        	personIdList.add(conof.getPersonId());
			}
	        if(personIdList!=null && personIdList.size()>0){
	        	for (String personId : personIdList) {
	        		conferenceGuestName+=personService.findPersonByPid(personId).getName()+" ";
				}
	        }
	        
//	        String personId=conference.getConferenceGuest();
//	        if(StringUtil.isNotEmpty(personId)){
//	        	personArray=personId.split(",");
//	        }
//	        if(personArray!=null){
//	        	for (String personIds : personArray) {
//	        		
//				}
//	        }
	        if(StringUtil.isNotEmpty(conferenceGuestName)){
	        	conference.setConferenceGuestName(conferenceGuestName);
	        }
	        conference.setResearchFieldNameStr(getDicCheckboxWorth(conference.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
	        conference.setAreaNameStr(getAreaWorth(conference.getArea(), conference.getDomesticOrForeign()));
	        model.addAttribute("conference", conference);
	        model.addAttribute("conferenceId", conferenceId);
	        return "showConferenceDetail";
	    }
	 
	 /**
		 * 下载详情附件
		 */
		@RequestMapping(value="/download",produces = "application/json;charset=UTF-8")
		@ResponseBody
		public void downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "beginDateTime1", required = false) String beginDateTime1, @RequestParam(value = "beginDateTime2", required = false) String beginDateTime2) {

			List<String> tagList = new ArrayList<>();
			List<List<String>> contentLists = Collections.synchronizedList(new ArrayList<List<String>>());
			//根据时间筛选
			Conference conference=new Conference();
			conference.setBeginDateTime1(beginDateTime1);
			conference.setBeginDateTime2(beginDateTime2);
			List<Conference> conList = conferenceService.queryAllConference(conference);
			
			tagList.add("活动ID");
			tagList.add("活动名称");
			tagList.add("开始时间");
			tagList.add("结束时间");
			tagList.add("所属领域");
			tagList.add("所在地区");
			
			for (Conference conf : conList) {
				List<String> content = new ArrayList<>();
				content.add("A"+conf.getConferenceNumber());
				content.add(conf.getConferenceName());
				content.add(conf.getConferenceDateTime());
				content.add(conf.getConferenceBeginTime());
				content.add(getDicCheckboxWorth(conf.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
				if(conf.getDomesticOrForeign()==1){
					content.add(getAreaWorth(String.valueOf(conf.getArea()), 1));
				}else if(conf.getDomesticOrForeign()==0){
					content.add(getAreaWorth(String.valueOf(conf.getArea()), 0));
				}
				contentLists.add(content);
			}
			//下载excel至服务器
			File file=ExcelUtil.writeExcel(tagList, contentLists, "conferenceList.xls");
			//将服务器上文件下载至本地
			try {
				ExcelUtil.downLoad(request, file, response);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
		
}
